package com.atom.wifiupload.nanohttpd;

import android.text.TextUtils;

import com.atom.wifiupload.WifiBookApp;
import com.atom.wifiupload.bean.FileBean;
import com.atom.wifiupload.utils.FileUtils;
import com.atom.wifiupload.utils.LogUtils;
import com.atom.wifiupload.utils.ServerDefaults;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ============================================================
 * project: WIFI-Upload
 * package: com.atom.wifiupload.wifitransfer
 * fileDescribe:
 * user: admin
 * email: 1299854942@qq.com
 * createTime: 2017/6/24  10:02
 * modify:
 * version:: V1.0
 * ============================================================
 **/
public class SimpleFileServer extends NanoHTTPD {

    private static SimpleFileServer server;

    public static SimpleFileServer getInstance() {
        if (null == server) {
            server = new SimpleFileServer(ServerDefaults.getPort());
        }
        return server;
    }

    public SimpleFileServer(int port) {
        super(port);
    }

    @Override
    public Response serve(IHTTPSession session) {
        String uri = session.getUri();
        NanoHTTPD.Method method = session.getMethod();
        Map<String, List<String>> parms = session.getParameters();
        Map<String, String> files = new HashMap<String, String>();

        if (NanoHTTPD.Method.PUT.equals(method) || NanoHTTPD.Method.POST.equals(method)) {
            try {
                session.parseBody(files);
            } catch (IOException ioe) {
                return newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
            } catch (NanoHTTPD.ResponseException re) {
                return newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
            }
            // 读取文件
            for (String s : files.keySet()) {
                try {
                    FileInputStream fis = new FileInputStream(files.get(s));
                    List<String> fileNames = parms.get("newfile");
                    String fileName = fileNames.get(0);
                    // 创建临时文件保存
                    // 创建目标文件
                    File desc = FileUtils.createWifiTranfesFile(fileName);
                    LogUtils.i("--" + desc.getAbsolutePath());

                    LogUtils.i("--" + desc.getAbsolutePath());
                    FileOutputStream fos = new FileOutputStream(desc);
                    byte[] buffer = new byte[1024];
                    while (true) {
                        int byteRead = fis.read(buffer);
                        if (byteRead == -1) {
                            break;
                        }
                        fos.write(buffer, 0, byteRead);
                    }
                    fos.flush();
                    fos.close();
                    // 添加到收藏
                    addToCollection(fileName, desc.getPath(), desc.length());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return newFixedLengthResponse("");
        } else if (NanoHTTPD.Method.GET.equals(method)) {
            try {
                uri = new String(uri.getBytes("ISO-8859-1"), "UTF-8");
                LogUtils.d("uri= " + uri);
            } catch (UnsupportedEncodingException e) {
                LogUtils.w("URL参数编码转换错误：" + e.toString());
            }

            //return new Response(HtmlConst.HTML_STRING);
            if (uri.contains("index.html") || uri.equals("/")) {
                return newFixedLengthResponse(Response.Status.OK, "text/html", new String(FileUtils.readAssets("/index.html")));
            } else if (uri.startsWith("/files/") && uri.endsWith(".txt")) {
                String bookid = uri.substring(7, uri.lastIndexOf("."));
                return newFixedLengthResponse(Response.Status.OK, "file", new String(FileUtils.getBytesFromFile(FileUtils.getChapterFile(bookid, 1))));
            } else {
                // 获取文件类型
                String end = uri.substring(uri.lastIndexOf(".") + 1).toLowerCase();
                String type = ServerDefaults.extensions.get(end);
                if (TextUtils.isEmpty(type))
                    return newFixedLengthResponse("");
                // 读取文件
                byte[] b = FileUtils.readAssets(uri);
                if (b == null || b.length < 1)
                    return newFixedLengthResponse("");
                // 响应
                return newChunkedResponse(Response.Status.OK, type, new ByteArrayInputStream(b));
            }
        }
        return newFixedLengthResponse("");
    }

    /**
     * 添加到收藏
     *
     * @param fileName
     */
    private void addToCollection(String fileName, String filePath, long size) {
        FileBean fileBean = new FileBean();
        fileBean.setFilename(fileName);
        fileBean.setFilepath(filePath);
        fileBean.setFileSize(size);
        fileBean.setCreateTime(System.currentTimeMillis());
        WifiBookApp.getDaoInstant().getFileBeanDao().insertOrReplace(fileBean);
    }

}
